//共用方法
function authAlet($ionicPopup, $location) {
  var alertPopup = $ionicPopup.alert({
    title: '警告',
    template: '你没有权限，请放弃该操作或联系管理员'
  });
  alertPopup.then(function (res) {
    $location.path('/tab/chats')
  });
}

function successAlert($ionicPopup, $timeout) {
  var alertPopup = $ionicPopup.alert({
    title: '提示',
    template: '操作成功'
  });
  alertPopup.then(function (res) {
    //console.log('Thank you for not eating my delicious ice cream cone')
  });
  $timeout(function () {
    alertPopup.close(); // 2秒后关闭弹窗
  }, 2000)
}

function erroAlert($ionicPopup, $timeout, msg) {
  var alertPopup = $ionicPopup.alert({
    title: '提示',
    template: '操作失败!' + msg
  });
  alertPopup.then(function (res) {
    //console.log('Thank you for not eating my delicious ice cream cone')
  });
  $timeout(function () {
    alertPopup.close(); // 2秒后关闭弹窗
  }, 2000)
}

//控制器
angular.module('starter.controllers', ['ionic'])
  .controller('DashCtrl', function ($scope, $rootScope, $state) {

  })
  .controller('ChatsCtrl', function ($scope, $rootScope, Chats, $ionicPopup, Teacher, Student) {
    // With the new view caching in Ionic, Controllers are only called
    // when they are recreated or on app start, instead of every page change.
    // To listen for when this page is active (for example, to refresh data),
    // listen for the $ionicView.enter event:
    //
    $scope.$on('$ionicView.enter', function (e) {
      userAuth = $rootScope.user;
      $scope.chats = Chats.all();
      $scope.data = Teacher.getLessons();
      $scope.data = Teacher.getStudents();
      $scope.data = Teacher.getCosts();
      $scope.data = Teacher.getCostsSize();
      $scope.data = Teacher.getCostsCount();
      $scope.data = Teacher.getSalaryList();
      $scope.data = Teacher.getSalaryCount();
      $scope.data = Student.getLessons();
      $scope.data = Student.getCosts();
      $scope.data = Student.getCostsCount();
      $scope.data = Student.getCostsSize();
      $scope.data = Student.getAction();
      $scope.data = Student.getIncome();
      $scope.data = Student.getIncomeCount();
    });

  })
  //功能
  .controller('ChatDetailCtrl', function ($scope, $rootScope, $stateParams, Chats, $ionicPopup, $location) {
    if (userAuth.degree == 'manager') {
      $scope.chat = Chats.get($stateParams.chatId);
    } else {
      authAlet($ionicPopup, $location);
    }
  })
  //学生交费
  .controller('ChatStuCostCtrl', function ($scope, $rootScope, $stateParams, Chats, $ionicPopup, $location, $http, Student) {
    if (userAuth.degree == 'manager' || userAuth.degree == 'student') {
      $scope.action = Student.getAction();
      $scope.income = Student.getIncome();
      $scope.incomeCount = Student.getIncomeCount();
      $scope.chat = Chats.get($stateParams.chatId);
      $('#findIncome').click(function () {
        var studentId = $rootScope.user.identity, actionId = $('#income-action :selected').attr('id');
        var startDate = $('#startDate').val(), endDate = $('#endDate').val(), num = $('#num').val();
        if (actionId == 'allAction') {
          actionId = ''
        }
        $http({
          method: 'POST',
          url: BASE_URL + 'appStudent/findIncome',
          params: {
            studentId: studentId,
            actionId: actionId,
            num: num,
            startDate: startDate,
            endDate: endDate
          },
          headers: {'Content-Type': 'application/json', 'charset': 'utf-8'}
        }).success(function (req) {
          if (req.msg) {
            $scope.income = req.data;
            $scope.incomeCount = req.count
          } else {
            //console.log('Student.getIncome.error')
          }
        })
      })
    } else {
      authAlet($ionicPopup, $location);
    }
  })
  //课程登记
  .controller('chatAddLessonCtrl', function ($scope, $rootScope, $stateParams, Chats, $ionicPopup, $location, Teacher, $http) {
    if (userAuth.degree == 'manager' || userAuth.degree == 'teacher') {
      var lessonId = 'allLesson', students = Teacher.getStudents(), user = $rootScope.user;
      var teacherId = user.identity;
      $('#addLesson-lesson').change(function () {
        lessonId = $('#addLesson-lesson  option:selected').attr("id");
        if (lessonId != 'allLesson') {
          $http({
            method: 'POST',
            url: BASE_URL + 'appTeacher/findStuByLesson?teacherId=' + teacherId + '&lessonId=' + lessonId,
            headers: {'Content-Type': 'application/json', 'charset': 'utf-8'}
          }).success(function (req) {
            if (req.msg) {
              $scope.students = req.data;
              //console.log('students:' + students)
            } else {
              //console.log('Teacher.getStudents.error')
            }
          });
        } else {
          $scope.students = Teacher.getStudents();
        }
      });
      $scope.lessons = Teacher.getLessons();
      $scope.students = students;
      $scope.chat = Chats.get($stateParams.chatId);
    } else {
      authAlet($ionicPopup, $location);
    }
  })
  //学生已上课程
  .controller('chatTeachLessonCtrl', function ($scope, $rootScope, $stateParams, Chats, $http, $ionicPopup, $location, Student) {
    if (userAuth.degree == 'manager' || userAuth.degree == 'student') {
      $scope.lessons = Student.getLessons();
      $scope.costs = Student.getCosts();
      $scope.count = Student.getCostsCount();
      $scope.num = Student.getCostsSize();
      $scope.chat = Chats.get($stateParams.chatId);
      $('#findLessonsForStu').click(function () {
        var studentId = $rootScope.user.identity, lessonId = $('#lesson :selected').attr('id');
        var startDate = $('#startDate').val(), endDate = $('#endDate').val();
        if (lessonId == 'allLesson') {
          lessonId = ''
        }
        $http({
          method: 'POST',
          url: BASE_URL + 'appStudent/findCost',
          params: {
            lessonId: lessonId,
            studentId: studentId,
            startDate: startDate,
            endDate: endDate
          },
          headers: {'Content-Type': 'application/json', 'charset': 'utf-8'}
        }).success(function (req) {
          if (req.msg) {
            $scope.costs = req.data;
            $scope.num = req.sum;
            $scope.count = req.count
          } else {
            //console.log('Teacher.getStudents.error')
          }
        })
      })
    } else {
      authAlet($ionicPopup, $location);
    }
  })
  //教师已上课程
  .controller('chatTeacherLessonCtrl', function ($scope, $rootScope, $stateParams, Chats, $http, $ionicPopup, $location, Teacher) {
    if (userAuth.degree == 'manager' || userAuth.degree == 'teacher') {
      $scope.lessons = Teacher.getLessons();
      $scope.students = Teacher.getStudents();
      $scope.num = Teacher.getCostsSize();
      $scope.count = Teacher.getCostsCount();
      $scope.costs = Teacher.getCosts();
      $scope.chat = Chats.get($stateParams.chatId);
      $scope.onDoubleTap = function (id) {
        var costId = id;
        $http({
          method: 'POST',
          url: BASE_URL + 'appTeacher/delLessons',
          params: {
            costId: costId
          },
          headers: {'Content-Type': 'application/json', 'charset': 'utf-8'}
        }).success(function (req) {
          if (req.msg) {
            $scope.costs = req.data;
            $scope.num = req.sum;
            $scope.count = req.count
          } else {
            console.log('Teacher.delLessons.error')
          }
        })
      };

      $('#findLessons').click(function () {
        var teacherId = $rootScope.user.identity, lessonId = $('#lesson :selected').attr('id'), studentId = $('#stus :selected').attr('id');
        var startDate = $('#startDate').val(), endDate = $('#endDate').val();
        if (studentId == 'allStus') {
          studentId = ''
        }
        if (lessonId == 'allLesson') {
          lessonId = ''
        }
        $http({
          method: 'POST',
          url: BASE_URL + 'appTeacher/findCost',
          params: {
            teacherId: teacherId,
            lessonId: lessonId,
            studentId: studentId,
            startDate: startDate,
            endDate: endDate
          },
          headers: {'Content-Type': 'application/json', 'charset': 'utf-8'}
        }).success(function (req) {
          if (req.msg) {
            $scope.costs = req.data;
            $scope.num = req.sum;
            $scope.count = req.count
          } else {
            //console.log('Teacher.getStudents.error')
          }
        })
      })
    } else {
      authAlet($ionicPopup, $location);
    }
  })
  //教师工资
  .controller('chatSalaryCtrl', function ($scope, $rootScope, $stateParams, Chats, $ionicPopup, $location, Teacher) {
    if (userAuth.degree == 'manager' || userAuth.degree == 'teacher') {
      $scope.salaryList = Teacher.getSalaryList();
      $scope.sum = Teacher.getSalaryCount();
      $scope.chat = Chats.get($stateParams.chatId);
    } else {
      authAlet($ionicPopup, $location);
    }
  })
  //活动报名
  .controller('chatActiveCtrl', function ($scope, $rootScope, $stateParams, Chats, $ionicPopup, $location) {
    if (userAuth.degree == 'manager' || userAuth.degree == 'student') {
      $scope.chat = Chats.get($stateParams.chatId);
    } else {
      authAlet($ionicPopup, $location);
    }
  })
  //设置
  .controller('AccountCtrl', function ($scope) {
    $scope.settings = {
      autoLogin: false,
      music: false,
      message: true
    }
  })
  //轮播页
  .controller('slideBox', function MyCtrl($scope, $ionicSlideBoxDelegate) {
    $scope.myActiveSlide = 0;
  })
  //通用查找页
  .controller('findPageCtrl', function ($scope) {
    $scope.show = {
      total: true,
      formShow: true,
      formHide: false,
      tableShow: true
    };
    $scope.del = {
      hide: false,
      show: true
    };
    $scope.showQuery = function () {
      $scope.show = {
        total: false,
        formShow: false,
        formHide: true,
        tableShow: false
      }
    };
    $scope.findByQuery = function () {
      $scope.show = {
        total: true,
        formShow: true,
        formHide: false,
        tableShow: true
      };
      $scope.del = {
        hide: false,
        show: true
      };
    };
    $scope.delCost = function () {
      $scope.del = {
        hide: true,
        show: false
      }
    }
  })
  //对话框 警告栏
  .controller('PopupCtrl', function ($scope, $ionicPopup, $timeout, $http, $location) {
    // 触发一个按钮点击，或一些其他目标
    //  confirm 对话框
    $scope.showConfirm = function () {
      //var lesson = AddLesson.lesson,n = AddLesson.n,date = AddLesson.date,teacherId = AddLesson.teacherId,
      //  lessonId = AddLesson,lessenId,students = AddLesson.students;
      var teacherId = userAuth.identity;
      var date = $('#addLesson-date').val();
      var lesson = $('#addLesson-lesson option:selected').text();
      var lessonId = $('#addLesson-lesson option:selected').attr('id');
      var students = [];
      $('#addLesson-stuList>li input:checked').each(function () {
        students.push($(this).val())
      });
      var n = students.length;
      var confirmPopup = $ionicPopup.confirm({
        title: '核对信息',
        template: '日期：' + date + ',课程：' + lesson + '，此次选中' + n + '个学生，确认提交信息吗？'
      });
      confirmPopup.then(function (res) {
        if (res) {
          $http({
            method: 'POST',
            url: BASE_URL + 'appTeacher/addLessons?teacherId=' + teacherId + '&lessonId=' + lessonId + '&date='
            + date + '&stuIdList=' + students,
            headers: {'Content-Type': 'application/json', 'charset': 'utf-8'}
          }).success(function (req) {
            if (req.msg) {
              //console.log('callback');
              $ionicPopup.alert({
                title: "提示",
                template: "操作成功！",
                okText: "知道了"
              }).then(function () {
                //console.log('Teacher.addLessons.success')
              })
            } else {
              //console.log('Teacher.addLessons.error')
            }
          });
          //console.log('You are sure')
        } else {
          //console.log('You are not sure')
        }
      })
    };
    //alert对话框
    $scope.showAlert = function () {
      var alertPopup = $ionicPopup.alert({
        title: '提示',
        template: '操作{成功或失败}'
      });
      alertPopup.then(function (res) {
        //console.log('Thank you for not eating my delicious ice cream cone')
      });
      $timeout(function () {
        alertPopup.close(); // 3秒后关闭弹窗
      }, 3000)
    };
    //alert警告框
    $scope.authAlert = function () {
      var alertPopup = $ionicPopup.alert({
        title: '警告',
        template: '你没有权限，请放弃该操作或联系管理员'
      });
      alertPopup.then(function (res) {
        //console.log('Thank you for not eating my delicious ice cream cone')
      });
      $timeout(function () {
        alertPopup.close(); // 3秒后关闭弹窗
      }, 3000)
    }
  })
  //用户登录
  .controller('userLoginCtrl', function ($scope, $http, $rootScope, $location, $ionicPopup) {
    var username = '0', password = '0';
    $scope.doLogin = function () {
      username = $('#user').val();
      password = $('#pwd').val();
      $http({
        method: 'POST',
        //url: BASE_URL + 'appUser/login?username=' + username + '&password=' + password,
        url: BASE_URL + 'appUser/login',
        type: 'json',
        params: {username: username, password: password},
        headers: {'Content-Type': 'application/json', 'charset': 'utf-8'}
      }).success(function (data) {
        if (data.result) {
          $rootScope.user = data.user;
          $rootScope.islogin = true;
          $location.path('/')
        } else {
          //alert对话框
          $ionicPopup.alert({
            title: '提示',
            template: data.msg
          });
        }
      })
    };
    $scope.closeLogin = function () {
      //关闭登陆框
    }
  })
  //用户信息界面
  .controller('userInfoCtrl', function ($scope, $http, $rootScope, $location, $ionicPopup, UserMenu, $stateParams) {
      $scope.$on('$ionicView.enter', function (e) {
        userAuth = $rootScope.user;
      });
      $scope.menuInfo = UserMenu.getInfo();
      $scope.menuSafe = UserMenu.getSafe();
      $scope.menu = UserMenu.getId($stateParams.menuId);
      $scope.logout = function () {
        $http({
          method: 'POST',
          url: BASE_URL + 'appUser/logout',
          headers: {'Content-Type': 'application/json', 'charset': 'utf-8'}
        }).success(function (req) {
          if (req.result) {
            $rootScope.user = {};
            $location.path('/login');
          } else {
            //console.log('Teacher.getLessons.error')
          }
        });
      }
    }
  )
  //个人信息详情
  .controller('userInfoDetail', function ($scope, $http, $rootScope, $location, $ionicPopup, $stateParams, $timeout, UserMenu) {
    $scope.menu = UserMenu.getId($stateParams.menuId);
    $scope.changeInfo = function () {
      var user = $rootScope.user;
      var name = $('#name').val(), phone = $('#phone').val(), identityCard = $('#identityCard').val();
      $http({
        method: 'POST',
        url: BASE_URL + 'appUser/changeInfo',
        params: {
          userId: user._id,
          id: user.identity,
          degree: user.degree,
          name: name,
          phone: phone,
          identityCard: identityCard
        },
        headers: {'Content-Type': 'application/json', 'charset': 'utf-8'}
      }).success(function (req) {
        if (req.result) {
          $rootScope.user = req.user;
          successAlert($ionicPopup, $timeout);
          $location.path('#/tab/userInfo');
        } else {
          var msg = '修改失败';
          erroAlert($ionicPopup, $timeout, msg);
          //console.log('Teacher.changePwd.error')
        }
      })
    }
  })
  //修改密码
  .controller('userChangePwd', function ($scope, $http, $rootScope, $location, $ionicPopup, $stateParams, $timeout, UserMenu) {
    $scope.menu = UserMenu.getId($stateParams.menuId);
    $scope.changePwd = function () {
      var lastPwd = $('#lastPwd').val(), newPwd = $('#newPwd').val(), checkPwd = $('#checkPwd').val();
      if (newPwd !== checkPwd) {
        $ionicPopup.alert({
          title: "提示",
          template: "新密码输入不一致！",
          okText: "知道了"
        })
      } else {
        $http({
          method: 'POST',
          url: BASE_URL + 'appUser/updatePwd?lastPwd=' + lastPwd + '&newPwd=' + newPwd,
          headers: {'Content-Type': 'application/json', 'charset': 'utf-8'}
        }).success(function (req) {
          if (req.result) {
            successAlert($ionicPopup, $timeout);
            $location.path('#/tab/userInfo');
          } else {
            var msg = '原密码错误！';
            erroAlert($ionicPopup, $timeout, msg);
            //console.log('Teacher.changePwd.error')
          }
        })
      }
    }
  });


